package io.bluerain.bocket.io;

import io.bluerain.bocket.callback.ReceiverHandler;
import io.bluerain.bocket.message.Message;
import io.bluerain.bocket.message.TextMessage;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

public class SubIo extends SocketIo {

    private ReceiverHandler receiverHandler;

    public SubIo(String addr, int port, Charset charset, ReceiverHandler receiverHandler) {
        this.charset = charset;
        this.receiverHandler = receiverHandler;
        try {
            this.client = new Socket(addr, port);
            Thread receiver = new Thread(new ReceiveSubThread(client));
            receiver.setDaemon(false);
            receiver.start();//开始接收服务端响应
        } catch (IOException e) {
            System.out.println("log - 连接失败");
        }
        try {
            this.outputStream = client.getOutputStream();
            this.out = new PrintStream(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected class ReceiveSubThread implements Runnable {

        private Socket socket;

        public ReceiveSubThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            boolean isCallback = receiverHandler != null ? true : false;
            BufferedReader br = null;
            try {
                inputStream = socket.getInputStream();
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String line;
            try {
                byte[] data;
                int len = -1;
                byte[] buf = new byte[1024];
                ByteArrayOutputStream output;

                while ((len = inputStream.read(buf)) != -1) {
                    output = new ByteArrayOutputStream();
                    output.write(buf, 0, len);
                    if (isCallback)
                        receiverHandler.receive(Message.make(output.toByteArray(), charset), inputStream);
                }
                /*while ((line = br.readLine()) != null) {
                    output = new ByteArrayOutputStream();
                    output.write(line.getBytes(), 0, line.getBytes().length);
                    if (isCallback)
                        receiverHandler.receive(Message.make(output.toByteArray(), charset));
                }*/
            } catch (IOException e) {
                System.out.println("连接丢失关闭读取流");
                try {
                    br.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
